<?php

namespace app\models;

use yii;
use yii\db\Query;

class PrintModel extends BaseModel
{
    public function __construct()
    {
        $this->table = yii::$app->db->tablePrefix . 'print_fee';
    }

    public function all($where = [], $offset = false, $limit = false, $order = false)
    {
        $db = new Query();
        $db->select('*')->from($this->table);
        if (!empty($where['begin_date'])) {
            $db->andWhere(['>=', 'date', $where['begin_date']]);
        }
        if (!empty($where['end_date'])) {
            $db->andWhere(['<=', 'date', $where['end_date']]);
        }
        if (!empty($where['invoice_order'])) {
            if (is_array($where['invoice_order'])) {
                $db->andWhere(['in', 'invoice_order', $where['invoice_order']]);
            } else {
                $db->andWhere(['invoice_order' => $where['invoice_order']]);
            }
        }
        if (!empty($where['name'])) {
            $db->andWhere(['name' => $where['name']]);
        }
        if ($order) {
            $db->orderBy($order);
        }
        if ($offset) {
            $db->offset($offset);
        }
        if ($limit) {
            $db->limit($limit);
        }
        return $db->all();
    }

    public function one($where = [])
    {
        $db = new Query();
        $db->select('*')->from($this->table);
        if (!empty($where['id'])) {
            $db->andWhere(['id' => $where['id']]);
        }
        return $db->limit(1)->one();
    }


    /**打印费size
     * @param array $where
     * @return int
     */
    public function size($where = [])
    {
        $db = new Query();
        $db->select('count(*) as num')->from($this->table);
        if (!empty($where['begin_date'])) {
            $db->andWhere(['>=', 'date', $where['begin_date']]);
        }
        if (!empty($where['end_date'])) {
            $db->andWhere(['<=', 'date', $where['end_date']]);
        }
        if (!empty($where['invoice_order'])) {
            $db->andWhere(['invoice_order' => $where['invoice_order']]);
        }
        if (!empty($where['name'])) {
            $db->andWhere(['name' => $where['name']]);
        }
        $info = $db->one();
        return $info ? $info['num'] : 0;
    }

    //打印费
    public function get_print_fee_by_invoice($invoice_arr)
    {
        $query = new Query();
        $query->select('*')
            ->from($this->table)
            ->where(['in', 'invoice_order', $invoice_arr]);

        $db = new Query();
        $list = $db->select('sum(fee) as fee,invoice_order')
            ->from(['a' => $query])
            ->groupBy('invoice_order')
            ->all();
        return $list;
    }


    //查询invoice的所有记录
    public function get_print_list_by_invoice($in)
    {
        $db = new Query();
        return $db->select('*')->from($this->table)->where(['invoice_order' => $in])->all();
    }


}
